//
//  DYPriceChoiceView.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2021/3/9.
//  Copyright © 2021 叁拾叁. All rights reserved.
//

import UIKit


class DYPriceChoiceView: SYBaseView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    var type: YuleType = .zhusu
    var priceClosure:((String,String)->Void)?
    var starClosure:((String)->Void)?
    var compClosure:((String)->Void)?
    
    var collectionView: UICollectionView!
    var priceTitles: [DYZSChoicePriceModel] = []//["0~150", "150~300", "300~450", "450~600", "600~1000", "1000以上"]
    var starTitles: [DYZSChoiceStartModel] = []//["经济型", "舒适/三星", "高档/四星", "豪华/五星"]
    var zhuanTitles: [DYZSChoiceStartModel] = []//["黄金钻酒店", "创享钻酒店"]
    
    var selectStarIds: [String] = []
    
    var priceSelectIndex: Int?
    
    var zsModel: DYZSPriceAndStarChoiceModel!
    
    var jqModels:[DYJQPriceChoiceModel]!
    
    var msModels:[DYJQPriceChoiceModel]!
    
    var header: DYPriceChoiceHeader?
    
    var bgView: UIButton = {
        let v: UIButton = UIButton()
        v.backgroundColor = UIColor.white
        v.layer.cornerRadius = 10.autoWidth()
        v.layer.masksToBounds = true
        return v
    }()
    
    var bgBt: UIButton = {
        let v: UIButton = UIButton()
        v.backgroundColor = UIColor(white: 0, alpha: 0.5)
        return v
    }()
    
    var compBt: UIButton = {
        let v: UIButton = UIButton()
        v.backgroundColor = Constant.blueColor
        v.layer.cornerRadius = 10.autoWidth()
        v.layer.masksToBounds = true
        v.setTitle("完成", for: .normal)
        v.setTitleColor(UIColor.white, for: .normal)
        v.titleLabel?.font = 18.autoBoldFontSize()
        return v
    }()
    
    func configure(_ model: DYZSPriceAndStarChoiceModel) {
        zsModel = model
        
    }
    
    func configure(_ models: [DYJQPriceChoiceModel]) {
        jqModels = models
    }
    
    func show() {
        self.isHidden = false
        switch self.type {
        case .zhusu:
            starTitles.removeAll()
            priceTitles = zsModel.price ?? []
            zsModel.start?.forEach({ (m) in
                if let _ = m.imgUrl {
                    
                    self.zhuanTitles.append(m)
                } else {
                    self.starTitles.append(m)
                }
            })
            priceTitles.forEach { (pm) in
                if let p = pm.strK, p.contains("以上") {
                    header?.highLb.text = pm.strK
                }
            }
            
        case .jingqu:
            priceTitles.removeAll()
            jqModels.forEach { (m) in
                var p = DYZSChoicePriceModel()
                p.strK = m.strK
                priceTitles.append(p)
            }
            
            priceTitles.forEach { (pm) in
                if let p = pm.strK, p.contains("以上") {
                    header?.highLb.text = pm.strK
                }
            }
            
        case .meishi:
            priceTitles.removeAll()
            jqModels.forEach { (m) in
                var p = DYZSChoicePriceModel()
                p.strK = m.strK
                priceTitles.append(p)
            }
            
            priceTitles.forEach { (pm) in
                if let p = pm.strK, p.contains("以上") {
                    header?.highLb.text = pm.strK
                }
            }
        }
        self.collectionView.reloadData()
    }
    
    override func initViews() {
        self.isHidden = true
        bgBt.addAction {[weak self] in
            if let `self` = self {
                self.isHidden = true
            }
        }
        compBt.addAction {[weak self] in
            if let `self` = self {
                self.isHidden = true
                var titles: [String] = []
                if let i = self.priceSelectIndex {
                    titles.append(self.priceTitles[i].strK ?? "")
                }
                self.starTitles.forEach { (m) in
                    if self.selectStarIds.contains(m.id ?? "") {
                        titles.append(m.strK ?? "")
                    }
                }
                self.zhuanTitles.forEach { (m) in
                    if self.selectStarIds.contains(m.id ?? "") {
                        titles.append(m.strK ?? "")
                    }
                }
                self.compClosure?(titles.joined(separator: ","))
            }
        }
        
        self.backgroundColor = .clear
        addSubview(bgBt)
        addSubview(bgView)
        addSubview(compBt)
        
        setCollectionView()
        bgView.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(10.autoWidth())
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(394.autoWidth() + BOTTOM_SAFE_HEIGHT)
        }
        bgBt.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        compBt.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-10.autoWidth() - BOTTOM_SAFE_HEIGHT)
            make.left.equalToSuperview().offset(15.autoWidth())
            make.right.equalToSuperview().offset(-15.autoWidth())
            make.height.equalTo(44.autoWidth())
        }
        collectionView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(25.autoWidth())
            make.left.equalToSuperview().offset(15.autoWidth())
            make.right.equalToSuperview().offset(-15.autoWidth())
            make.height.equalTo(300.autoWidth())
        }
    }
    
    func setCollectionView() {
        
        
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        let itemWidth = SCREEN_WIDTH / 4
        //        layout.itemSize = CGSize(width: itemWidth - 10, height: 76.5)
        layout.minimumLineSpacing = 5
        layout.minimumInteritemSpacing = 5
        layout.scrollDirection = .vertical
        
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.showsHorizontalScrollIndicator = false
        
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(DYPriceChoiceCell.self, forCellWithReuseIdentifier: NSStringFromClass(DYPriceChoiceCell.self))
        collectionView.register(DYPriceChoiceTypeCell.self, forCellWithReuseIdentifier: NSStringFromClass(DYPriceChoiceTypeCell.self))
        collectionView.register(DYPriceChoiceHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "DYPriceChoiceHeader")
        collectionView.register(DYPriceChoiceStarHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "DYPriceChoiceStarHeader")
        collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "UICollectionReusableView")
        
        
        self.bgView.addSubview(self.collectionView)
    }
    
    func refreshItems(arr: [Any], section: Int) {
        for (i,_) in arr.enumerated() {
            self.collectionView.reloadItems(at: [IndexPath(item: i, section: section)])
        }
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        switch self.type {
        case .zhusu:
            return 3
        case .jingqu:
            return 1
        case .meishi:
            return 1
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            
            return priceTitles.count
        } else  if section == 1 {
            return starTitles.count
        } else {
            return zhuanTitles.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if indexPath.section == 0 {
            let cell: DYPriceChoiceCell? = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(DYPriceChoiceCell.self), for: indexPath) as? DYPriceChoiceCell
            if let d = priceTitles.objectAtIndex(index: indexPath.row) {
                if let i = priceSelectIndex, i == indexPath.row {
                    cell?.configCell(d, true)
                } else {
                    cell?.configCell(d)
                }
            }
            return cell!
        } else if indexPath.section == 1 {
            let cell: DYPriceChoiceCell? = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(DYPriceChoiceCell.self), for: indexPath) as? DYPriceChoiceCell
            if let d = starTitles.objectAtIndex(index: indexPath.row) {
                if selectStarIds.contains(d.id ?? "") {
                    cell?.configCell(d, true)
                } else {
                    cell?.configCell(d)
                }
            }
            return cell!
        } else {
            let cell: DYPriceChoiceTypeCell? = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(DYPriceChoiceTypeCell.self), for: indexPath) as? DYPriceChoiceTypeCell
            var select = false
            if selectStarIds.contains(zhuanTitles[indexPath.row].id ?? "") {
                select = true
            }
            if indexPath.row == 0 {
                cell?.configure(zhuanTitles[0], select)
            } else {
                cell?.configure(zhuanTitles[1], select)
            }
            return cell!
        }
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if indexPath.section == 0 {
            header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "DYPriceChoiceHeader", for: indexPath) as? DYPriceChoiceHeader
            return header!
        } else if indexPath.section == 1 {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "DYPriceChoiceStarHeader", for: indexPath)
            return header
        } else {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "UICollectionReusableView", for: indexPath)
            return header
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        if section == 0 {
            return CGSize(width: SCREEN_WIDTH, height: 72.autoWidth())
        } else if section == 1 {
            return CGSize(width: SCREEN_WIDTH, height: 45.autoWidth())
        } else {
            return CGSize(width: SCREEN_WIDTH, height: 5.autoWidth())
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell: DYPriceChoiceCell? = collectionView.cellForItem(at: indexPath) as? DYPriceChoiceCell
        if indexPath.section == 0 {
            let low = cell?.low ?? 0.0
            let high = cell?.high ?? 0.0
            header?.rangeSlider.lowerValue = low
            header?.rangeSlider.upperValue = high
            if high == 1 {
                let p = Int(low * 1000)
                header?.priceLb.text = "¥\(p)以上"
                self.priceClosure?("\(p)", "")
            } else {
                let r = Int(low * 1000)
                let h = Int(high * 1000)
                header?.priceLb.text = "¥\(Int(low * 1000))~¥\(Int(high * 1000))"
                self.priceClosure?("\(r)", "\(h)")
            }
            priceSelectIndex = indexPath.row
            
            self.refreshItems(arr: priceTitles, section: 0)
        } else if indexPath.section == 1 {
            
            let id = starTitles[indexPath.row].id ?? ""
            if selectStarIds.contains(id) {
                self.selectStarIds = self.selectStarIds.filter { $0 != id }
            } else {
                self.selectStarIds.append(id)
            }
            
            self.starClosure?(selectStarIds.joined(separator: ","))
            
            self.refreshItems(arr: starTitles, section: 1)
            self.refreshItems(arr: zhuanTitles, section: 2)
        } else {
            
            let id = zhuanTitles[indexPath.row].id ?? ""
            if selectStarIds.contains(id) {
                self.selectStarIds = self.selectStarIds.filter { $0 != id }
            } else {
                self.selectStarIds.append(id)
            }
            
            self.starClosure?(selectStarIds.joined(separator: ","))
            
            self.refreshItems(arr: starTitles, section: 1)
            self.refreshItems(arr: zhuanTitles, section: 2)
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.section == 0 {
            return CGSize(width: 82.autoWidth(), height: 35.autoWidth())
        } else if indexPath.section == 1 {
            return CGSize(width: 82.autoWidth(), height: 35.autoWidth())
        } else {
            return CGSize(width: 170.autoWidth(), height: 50.autoWidth())
        }
        
    }
}



class DYPriceChoiceCell: UICollectionViewCell {
    
    
    fileprivate var titleLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 12.autoFontSize()
        
        return v
    }()
    
    var low: Double = 0.0
    
    var high: Double = 0.0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public func configCell(_ model: DYZSChoicePriceModel, _ isSelect: Bool? = false) {
        
        titleLb.text = model.strK
        if let p = model.strK {
            
            if p.contains("以上") {
                low = 1.0
                high = 1.0
            } else {
                let pStr = p.replacingOccurrences(of: "¥", with: "")
                low = (Double(pStr.components(separatedBy: "~").first ?? "") ?? 0.0)/1000.0
                high = (Double(pStr.components(separatedBy: "~").last ?? "") ?? 0.0)/1000.0
            }
        }
        if isSelect == true {
            self.backgroundColor = Constant.blueColor
            titleLb.textColor = .white
        } else {
            self.backgroundColor = Constant.bgViewColor
            titleLb.textColor = UIColor(hex: 0x3E3E3E)
        }
    }
    
    public func configCell(_ model: DYZSChoiceStartModel, _ isSelect: Bool? = false) {
        
        var m: DYZSChoicePriceModel = DYZSChoicePriceModel()
        m.strK = model.strK
        self.configCell(m, isSelect)
    }
    
    fileprivate func initViews() {
        
        self.layer.cornerRadius = 4.autoWidth()
        self.layer.masksToBounds = true
        addSubview(titleLb)
        titleLb.snp.makeConstraints { (make) in
            
            make.center.equalToSuperview()
            make.height.equalTo(12.0.autoWidth())
        }
    }
}

class DYPriceChoiceTypeCell: UICollectionViewCell {
    
    
    fileprivate var titleLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 13.autoFontSize()
        
        return v
    }()
    
    fileprivate var subTitleLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 10.autoFontSize()
        
        return v
    }()
    
    let imgView: UIImageView = {
        let v = UIImageView()
        return v
    }()
    
    func configure(_ model: DYZSChoiceStartModel, _ isSelect: Bool) {
        
        titleLb.text = model.strK
        subTitleLb.text = model.synopsis
        imgView.sy_setWithUrl(model.imgUrl)
        if isSelect == true {
            self.backgroundColor = Constant.blueColor
            titleLb.textColor = .white
            subTitleLb.textColor = .white
        } else {
            self.backgroundColor = Constant.bgViewColor
            titleLb.textColor = UIColor(hex: 0x3E3E3E)
            subTitleLb.textColor = UIColor(hex: 0x666666)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public func configCell(_ title: String) {
        
        titleLb.text = title
    }
    
    fileprivate func initViews() {
        
        self.layer.cornerRadius = 4.autoWidth()
        self.layer.masksToBounds = true
        addSubview(titleLb)
        addSubview(subTitleLb)
        addSubview(imgView)
        titleLb.snp.makeConstraints { (make) in
            
            make.top.equalToSuperview().offset(12.autoWidth())
            make.left.equalToSuperview().offset(70.autoWidth())
            make.height.equalTo(13.0.autoWidth())
        }
        
        subTitleLb.snp.makeConstraints { (make) in
            
            make.top.equalToSuperview().offset(28.autoWidth())
            make.left.equalToSuperview().offset(70.autoWidth())
            make.height.equalTo(11.0.autoWidth())
        }
        
        imgView.snp.makeConstraints { (make) in
            
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(36.autoWidth())
            make.width.equalTo(23.autoWidth())
            make.height.equalTo(18.0.autoWidth())
        }
    }
}


class DYPriceChoiceStarHeader: UICollectionReusableView {
    
    
    fileprivate var titleLb: UILabel = {
        let v: UILabel = UILabel()
        v.text = "星级"
        v.textColor = UIColor(hex: 0x333333)
        v.font = 16.autoFontSize()
        return v
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    fileprivate func initViews() {
        
        addSubview(titleLb)
        titleLb.snp.makeConstraints { (make) in
            
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.height.equalTo(45.0.autoWidth())
        }
    }
}


class DYPriceChoiceHeader : UICollectionReusableView {
    
    var lastLow: Double = 0.0
    var lastHigh: Double = 1.0
    var sliderChangeClosure: ((Double, Double)->Void)?
    fileprivate var titleLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 16.autoFontSize()
        v.textColor = UIColor(hex: 0x333333)
        v.text = "价格"
        return v
    }()
    
    var priceLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 16.autoFontSize()
        v.textColor = Constant.redColor
        
        return v
    }()
    
    fileprivate var lowLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 11.autoFontSize()
        v.textColor = UIColor(hex: 0x333333)
        v.text = "¥0"
        return v
    }()
    
    var highLb: UILabel = {
        let v: UILabel = UILabel()
        v.font = 11.autoFontSize()
        v.textColor = UIColor(hex: 0x333333)
        
        return v
    }()
    
    // 播放进度
    //    fileprivate var slider: SYSlider = {
    //        let slid: SYSlider = SYSlider()
    //        slid.setThumbImage(UIImage(named: "price_dot"), for: .normal)
    //        slid.addTarget(self, action: #selector(sliderAction), for: .touchUpInside)
    //        slid.maximumTrackTintColor = Constant.bgViewColor
    //        slid.minimumTrackTintColor = Constant.blueColor
    //        slid.setValue(0.8, animated: false)
    //        slid.isHidden = true
    //        return slid
    //    }()
    
    var rangeSlider:SYRangeSlider = {
        let v = SYRangeSlider()
        v.addTarget(self, action: #selector(rangeSliderValueChanged), for: .touchUpInside)
        v.trackHighlightTintColor = Constant.blueColor!
        v.trackTintColor = Constant.bgViewColor!
        v.trackHeight = 2
        v.lowerValue = 0.0
        v.upperValue = 1.0
        return v
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public func configCell(_ title: String) {
        
        titleLb.text = title
    }
    
    fileprivate func initViews() {
        
        addSubview(titleLb)
        addSubview(priceLb)
        addSubview(lowLb)
        addSubview(highLb)
        addSubview(rangeSlider)
        
        rangeSlider.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(50.0.autoWidth())
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(20.autoWidth())
        }
        priceLb.snp.makeConstraints { (make) in
            
            make.top.equalToSuperview()
            make.left.equalToSuperview().offset(40.0.autoWidth())
            make.height.equalTo(16.0)
        }
        titleLb.snp.makeConstraints { (make) in
            
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.height.equalTo(16.0)
        }
        lowLb.snp.makeConstraints { (make) in
            
            make.top.equalToSuperview().offset(34.autoWidth())
            make.left.equalToSuperview()
            make.height.equalTo(11.0)
        }
        highLb.snp.makeConstraints { (make) in
            
            make.top.equalToSuperview().offset(34.autoWidth())
            make.right.equalToSuperview()
            make.height.equalTo(11.0)
        }
    }
    
    @objc func rangeSliderValueChanged(sender: SYRangeSlider) {
        
        print("rangeSliderValueChanged.value ====== \(sender.lowerValue),\(sender.upperValue)")
        
        let lowInt: Int = Int(sender.lowerValue * Double(1000) / 50)
        var low: Int = 0
        
        let highInt: Int = Int(sender.upperValue * Double(1000) / 50)
        var high: Int = 0
        
        if lastLow != sender.lowerValue {
            
            if lastLow < sender.lowerValue {// 当low往右滑动时 加1格
                
                // 防止low和hight相等
                if sender.upperValue - sender.lowerValue > 1/20 {
                    low = lowInt*50 + 50
                    rangeSlider.lowerValue = Double(low)/1000
                    
                } else {
                    low = lowInt*50
                    rangeSlider.lowerValue = Double(low)/1000
                }
                
            } else {// 当low往左滑动时 减1格
                low = lowInt*50
                rangeSlider.lowerValue = Double(low)/1000
            }
            
            lastLow = rangeSlider.lowerValue
        } else {
            low = lowInt*50
        }
        
        if lastHigh != sender.upperValue {
            
            if lastHigh < sender.upperValue {// 当high往右滑动时 加1格
                high = highInt*50 + 50
                rangeSlider.upperValue = Double(high)/1000
            } else {// 当high往左滑动时 减1格
                
                // 防止low和hight相等
                if sender.upperValue - sender.lowerValue > 1/20 {
                    high = highInt*50
                    rangeSlider.upperValue = Double(high)/1000
                } else {
                    high = highInt*50 + 50
                    rangeSlider.upperValue = Double(high)/1000
                }
            }
            
            lastHigh = rangeSlider.upperValue
        } else {
            high = highInt*50
        }
        
        if sender.upperValue == 1 {
            priceLb.text = "¥\(low)以上"
        } else {
            priceLb.text = "¥\(low)~¥\(high)"
        }
        
        if let closure = sliderChangeClosure {
            closure(rangeSlider.lowerValue, rangeSlider.upperValue)
            print("rangeSliderValueChanged.value ++++ \(rangeSlider.lowerValue),\(rangeSlider.upperValue)")
        }
    }
}
